<?php
/**
 * 系统异步定时任务数据模型类
 *
 * @author liang<lang@vip.deyi.com>
 * @since   2015/8/26 11:17
 * @copyright  deyi.com
 */
namespace Apps\Common\Model;

use Apps\Common\Constant\CacheKeyConstant;
use Deyi\Functions\CacheFunction;

/**
 * Class TaskCron
 * @package Apps\Common\Model
 */
class TaskCron extends BaseModel
{
    protected static $_DBNAME = 'api';


    protected static $_TABLENAME = 'task_cron';

    /**
     *  获取任务列表
     *
     * @author liang<lang@vip.deyi.com>
     * @return bool|\Phalcon\Mvc\Model\Resultset\Simple
     */
    public function getTaskList()
    {
        //读取加锁,避免多个进程都执行cron
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::TASK_CRON_MUTEX_LOCK_CACHE_KEY, date('Y-m-d H:i'));

        //检查锁是否没有ttl过期时间，如果没有就清理掉重新设置
        if (static::$_redis->ttl($cacheKey) === -1) {
            static::$_redis->delete($cacheKey);
        }

        if (static::$_redis->set($cacheKey, 1, ['nx', 'ex' => 3600])) {

            $sql = 'SELECT * FROM ' . static::$_TABLENAME;

            return $this->select($sql);
        } else {
            static::$_logger->error('#global task lock#');
            return false;
        }
    }

    public function deleteById($id)
    {
        $sql = 'DELETE FROM ' . static::$_TABLENAME . ' WHERE id=?';

        return $this->execute($sql, [$id]);
    }


    public function insert($taskName, $taskData, $cron, $once)
    {
        $sql = 'INSERT INTO ' . static::$_TABLENAME . '(taskname,taskdata,cron,once) VALUES(?,?,?,?)';

        return $this->execute($sql, [$taskName, $taskData, $cron, $once]);
    }

    public function getAllTaskList()
    {
        $sql = 'SELECT * FROM ' . static::$_TABLENAME;

        return $this->select($sql);
    }

}
